"""
服务器管理模块
包含多个MCP服务器实现
"""

import asyncio
from typing import Dict, List
from mcp.server.fastmcp import FastMCP

from .servers import (
    VoiceServer,
    UltrasonicServer,
    CameraServer,
    IMUServer,
    MotionServer,
    ServoServer,
    StatusServer,
    ConfigServer,
)


class MCPServersManager:
    """MCP服务器管理类

    负责管理所有MCP服务器的生命周期,提供统一的启动和停止接口
    """

    def __init__(self):
        """初始化服务器管理器"""
        self.servers: Dict[str, FastMCP] = {}
        self.server_tasks: Dict[str, asyncio.Task] = {}

        # 初始化所有服务器
        self._init_servers()

    def _init_servers(self):
        """初始化所有MCP服务器"""
        self.servers = {
            "voice": VoiceServer(),
            "ultrasonic": UltrasonicServer(),
            "camera": CameraServer(),
            "imu": IMUServer(),
            "motion": MotionServer(),
            "servo": ServoServer(),
            "status": StatusServer(),
            "config": ConfigServer(),
        }

    async def start(self):
        """启动所有MCP服务器"""
        for server_name, server in self.servers.items():
            try:
                # 启动服务器并保存任务
                task = asyncio.create_task(server.run(transport="stdio"))
                self.server_tasks[server_name] = task
                print(f"Started MCP server: {server_name}")
            except Exception as e:
                print(f"Failed to start server {server_name}: {str(e)}")

    async def stop(self):
        """停止所有MCP服务器"""
        for server_name, task in self.server_tasks.items():
            try:
                # 取消服务器任务
                task.cancel()
                await task
                print(f"Stopped MCP server: {server_name}")
            except asyncio.CancelledError:
                print(f"Server {server_name} cancelled successfully")
            except Exception as e:
                print(f"Error stopping server {server_name}: {str(e)}")

        # 清空任务列表
        self.server_tasks.clear()

    def get_server(self, server_name: str) -> FastMCP:
        """获取指定名称的服务器实例

        Args:
            server_name: 服务器名称

        Returns:
            FastMCP: 服务器实例

        Raises:
            KeyError: 如果服务器不存在
        """
        return self.servers[server_name]

    def list_servers(self) -> List[str]:
        """获取所有服务器名称列表

        Returns:
            List[str]: 服务器名称列表
        """
        return list(self.servers.keys())
